import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  FlatList
} from 'react-native'

import { connect } from 'react-redux'
import HeaderDefault from '../../components/header/HeaderDefault'
import { getTodayTourInfusionTask } from '../../netServer/patrol'
import Toast from 'react-native-simple-toast'
import { Empty } from '../../components/Empty/Empty'

class PatorlInfusion extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectOralMedic: null,
      taskList: [],
      isFresh: false,
      timeMark: new Date()
    }
  }
  static navigationOptions = ({ navigation }) => ({
    header: (
      <HeaderDefault backBtnOnPress={navigation.goBack} title="输液巡视" />
    )
  })

  _keyExtractor = (item, index) => 'shuyexunshi' + index

  _separator = () => {
    return <View style={{ height: 1, backgroundColor: '#efefef' }} />
  }

  componentDidMount() {
    this.timer = setInterval(this._markTimer, 1000)

    this._loadInfusionTask()
  }

  _refreshData = () => {
    this.setState({
      isFresh: true
    })
    this._loadInfusionTask()
  }

  _loadInfusionTask = () => {
    let params = new FormData()

    let { user_id } = this.props.user_info
    params.append('userId', user_id)

    getTodayTourInfusionTask(params, resp => {
      let { code, data = [], msg } = resp

      if (code == '0') {
        this.setState({
          taskList: data,
          isFresh: false
        })
      } else {
        Toast.showWithGravity(msg, 0.3, Toast.CENTER)
        this.setState({
          taskList: [],
          isFresh: false
        })
      }
    })
  }

  componentWillUnmount() {
    this.timer && clearInterval(this.timer)
  }

  _markTimer = () => {
    let nowTime = new Date()
    this.setState({
      timeMark: nowTime
    })
  }

  _getTimeStr(begingStr) {
    let t1 = begingStr
    if (!t1) return ''
    let dateBegin = new Date(t1)
    if (!dateBegin) return ''
    let dateEnd = this.state.timeMark
    let timeTotal = dateEnd.getTime() - dateBegin.getTime()

    //计算出相差天数
    var days = Math.floor(timeTotal / (24 * 3600 * 1000))

    //计算出小时数

    var leave1 = timeTotal % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000))
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000))

    //计算相差秒数
    var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000)

    if (days > 0) {
      // 3天0时45分56秒
      return days + '天' + hours + '时' + minutes + '分'
    } else {
      if (hours > 0) {
        // 3天0时45分56秒
        return hours + '时' + minutes + '分'
      } else {
        return minutes + '分'
      }
    }
  }

  _renderItem = ({ item }) => {
    let { start_time, bed_no, status, advList = [] } = item

    return (
      <TouchableOpacity
        onPress={() => {
          this.props.navigation.navigate('PatorlInfusionResult', {
            taskInfo: item,
            callBack: this._loadInfusionTask
          })
        }}
      >
        <View
          style={{
            width: screenWidth,
            backgroundColor: 'white',
            borderBottomColor: '#efefef',
            borderBottomWidth: 1,
            flexDirection: 'row',
            alignItems: 'center'
          }}
        >
          <Text
            style={{
              color: 'blue',
              fontSize: 14,
              width: 70,
              textAlign: 'center'
            }}
          >
            {this._getTimeStr(start_time.replace(/-/g, '/'))}
          </Text>

          <View style={{ flex: 1 }}>
            {advList.map((value, index) => {
              return (
                <View key={index}>
                  <Text style={{ lineHeight: 30 }}>{value.medName}</Text>
                  <Text style={{ lineHeight: 30 }}>
                    {value.standard}/{value.use_unit}&nbsp;&nbsp;&nbsp;&nbsp;
                    {value.measure}
                  </Text>
                </View>
              )
            })}
          </View>
          <View
            style={{
              width: 80,
              height: 80,
              paddingTop: 10,
              paddingBottom: 10,
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            <Text style={{ lineHeight: 30, fontWeight: 'bold' }}>{bed_no}</Text>
            <Text style={{ lineHeight: 30, color: '#e30000' }}>{status}</Text>
          </View>
        </View>
      </TouchableOpacity>
    )
  }

  _headerComponent() {
    return (
      <View
        style={{
          width: screenWidth,
          height: 30,
          paddingLeft: 10,
          paddingRight: 10,
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          borderBottomColor: '#efefef',
          borderBottomWidth: 1
        }}
      >
        <Text>计时器</Text>
        <Text>药品名</Text>
        <Text>床号/状态</Text>
      </View>
    )
  }

  _ListEmptyComponent = () => {
    return <Empty titleStr="暂时没有相关的数据" />
  }

  render() {
    return (
      <View style={styles.container}>
        {this._headerComponent()}

        <FlatList
          refreshing={this.state.isFresh}
          onRefresh={this._refreshData}
          ListEmptyComponent={this._ListEmptyComponent}
          style={{ flex: 1 }}
          ItemSeparatorComponent={this._separator}
          data={this.state.taskList}
          extraData={this.state.timeMark}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white'
  }
})

function select(store) {
  return { user_info: store.userInfo.user_info }
}

export default connect(select)(PatorlInfusion)
